package com.xxx.netty.eventloop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * EventLoopServer端
 */
@Slf4j
public class EventLoopServer {

    public static void main(String[] args) {
        // 再次细分工：将handler里的操作从worker线程交给单独的EventLoopGroup来处理
        EventLoopGroup executorGroup = new DefaultEventLoop();

        // Server端启动入库
        new ServerBootstrap()
                // 细化分工1：定义2个EventLoopGroup: boss（负责accept事件） 和 worker（负责read和write事件），其中worker由2个线程组成
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                // server端使用NioServerSocketChannel
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter(){  // 添加第1个handler
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info(buf.toString(Charset.defaultCharset()));
                                ctx.fireChannelRead(msg);  // 将消息传递给下一个handler
                            }
                        }).addLast(executorGroup, "handler2", new ChannelInboundHandlerAdapter(){  // 添加第2个handler
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
